# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iCalendar import CalendarGUI
from iArea import CountryListGUI


class TaxGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Tax")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgCalendar=PhotoImage(file="img/calendar.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Tax-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Tax-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tTaxGUI\tStart")
		self.makeTax()

	# DEBUT de la gestion du module Tax ------------------------------------------------------------------------------------------------------------------
	def clearFieldTax(self):
		# Mise a zéro des champs de la fiche taxe
		self.taxValues[0].set("")
		self.taxValues[1].set("")
		self.taxValues[2].set("")
		self.taxValues[3].set("")
		self.taxValues[4].set("")
		self.taxValues[5].set("")
		self.listObject=[State,]

	def selectTax(self, event):
		if self.listTax.get(0)!="":
			result = Tax.select(Tax.q.id==self.idListTax[int(self.listTax.curselection()[0])])
			for row in result:
				self.selectedTax = row
			self.listObject[0]=self.selectedTax.country
			self.taxValues[0].set(self.listObject[0].name)
			if self.selectedTax.code != None:self.taxValues[1].set(self.selectedTax.code)
			if self.selectedTax.designation != None:self.taxValues[2].set(self.selectedTax.designation)
			if self.selectedTax.rate != None:self.taxValues[3].set(self.selectedTax.rate)
			if self.selectedTax.dateIn != None:
				# Affichage de la date de Début (self.selectedTax .dateIn)
				self.taxValues[4].set(self.selectedTax.dateIn.strftime("%d/%m/%Y"))
			if self.selectedTax.dateOut != None:
				# Affichage de la date de Fin (self.selectedTax .dateOut)
				self.taxValues[5].set(self.selectedTax.dateOut.strftime("%d/%m/%Y"))
			# activation du bouton supprimer
			self.deleteTaxBt.config(state=NORMAL)

	def searchTax(self, event=None):
		if self.searchTaxValue.get() != "":
			self.listTax.delete(0,END)
			self.idListTax = []
			result = Tax.select(Tax.q.designation.startswith(self.searchTaxValue.get().encode("utf-8")), orderBy=Tax.q.designation)
			for row in result:
				self.listTax.insert(END, row.code+" - "+row.designation+" - "+row.dateIn.strftime("%d/%m/%Y"))
				self.idListTax.append(row.id)
		else:
			self.listTax.delete(0,END)
			self.idListTax = []
			result = Tax.select(orderBy=Tax.q.designation)
			for row in result:
				self.listTax.insert(END, row.code+" - "+row.designation+" - "+row.dateIn.strftime("%d/%m/%Y"))
				self.idListTax.append(row.id)

	def makeTax(self):
		leftFrame = Frame(self)
		# Fiche Tax  (présentation colonne de gauche)
		Label(leftFrame, text=u"Taxe").pack(side=TOP, fill=X)
		# Création des champs a renseigner pour un object Tax
		taxLabels = (u"Pays", u"Code", u"Désignation",u"Taux", u"Début (date)", u"Fin (date)")
		self.taxValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
		count = 0
		for name in taxLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Pays lié a la tax
				Entry(f, textvariable=self.taxValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myState=Button(f, image=self.imgSearch, command=lambda x=self.taxValues[count]:self.ctrlListState(x), padx=4, pady=1)
				myState.pack(side=RIGHT)
				self.balloon.bind(myState, u"Séléctionner un Pays")
			elif count == 4: # Date de Début
				Entry(f, textvariable=self.taxValues[count], width=21).pack(side=LEFT, fill=X)
				myCal1=Button(f, image=self.imgCalendar, command=lambda x=self.taxValues[count]:self.ctrlCalendar(x), padx=4, pady=1)
				myCal1.pack(side=LEFT)
				self.balloon.bind(myCal1, u"Calendrier")
			elif count == 5: # Date de Fin
				Entry(f, textvariable=self.taxValues[count], width=21).pack(side=LEFT, fill=X)
				myCal2=Button(f, image=self.imgCalendar, command=lambda x=self.taxValues[count]:self.ctrlCalendar(x), padx=4, pady=1)
				myCal2.pack(side=LEFT)
				self.balloon.bind(myCal2, u"Calendrier")
			else: 
				Entry(f, textvariable=self.taxValues[count], width=24).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveTaxBt=Button(s, image=self.imgSave, command=self.createTax)
		self.saveTaxBt.bind("<Return>", self.createTax)
		self.saveTaxBt.pack(side=LEFT)
		self.balloon.bind(self.saveTaxBt, u"Enregistrer")
		self.deleteTaxBt=Button(s, image=self.imgDelete, command=self.deleteTax, state=DISABLED)
		self.deleteTaxBt.bind("<Return>", self.deleteTax)
		self.deleteTaxBt.pack(side=LEFT)
		self.balloon.bind(self.deleteTaxBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Taxes").pack(side=TOP, fill=X)
		self.searchTaxValue = StringVar()
		self.searchTaxEt = Entry(leftFrame,  width=32, textvariable=self.searchTaxValue, relief=GROOVE)
		self.searchTaxEt.bind("<KeyRelease>", self.searchTax)
		self.searchTaxEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchTaxEt, u"Saisir les premières lettres d'une Tax\npour une recherche plus précise,\nla liste est classée par désignation.")
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listTax = Listbox(s)
		self.listTax.config(yscrollcommand=scrollbar.set, width=37, selectmode=SINGLE, height=10)
		self.listTax.bind("<ButtonRelease-1>",self.selectTax)
		scrollbar.config(command=self.listTax.yview)
		self.listTax.pack()
		self.balloon.bind(self.listTax, u"Séléctionner une Tax\npour la visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.clearFieldTax()
		self.searchTax()

	def ctrlCalendar(self,field):
		CalendarGUI(field=field, log=self.log, path=self.path)

	def ctrlListState(self,field):
		CountryListGUI(balloon=self.balloon,field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)

	def getDateTimeInTax(self):
		if self.taxValues[4].get() != "":
			date=self.taxValues[4].get().split("/")
			d = datetime.date(int(date[2]), int(date[1]), int(date[0]))
			return d
		else:
			return None

	def getDateTimeOutTax(self):
		if self.taxValues[5].get() != "":
			date=self.taxValues[5].get().split("/")
			d = datetime.date(int(date[2]), int(date[1]), int(date[0]))
			return d
		else:
			return None

	def verifyTax(self):
		if self.taxValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Pays est obligatoire !\nMerci de le compléter.")
			return False
		elif self.taxValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Code est obligatoire !\nMerci de le compléter.")
			return False
		elif self.taxValues[2].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Désignation est obligatoire !\nMerci de le compléter.")
			return False
		elif self.taxValues[3].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Taux est obligatoire !\nMerci de le compléter.")
			return False
		elif self.taxValues[4].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Début date est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createTax(self, event=None):
		if self.verifyTax():
			if  self.deleteTaxBt.config()["state"][4] == "normal":
				self.modifyTax()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme une nouvelle Tax ?\n" % self.taxValues[2].get()):
					Tax(country=self.listObject[0],
						code=self.taxValues[1].get().encode("utf-8"),
						designation=self.taxValues[2].get().encode("utf-8"),
						rate=self.taxValues[3].get().encode("utf-8"),
						dateIn=self.getDateTimeInTax(),
						dateOut=self.getDateTimeOutTax(),
						createDate=datetime.datetime.now()
					)
					self.searchTax()
				self.clearFieldTax()

	def modifyTax(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier la Tax %s ?" % self.selectedTax.designation):
			self.selectedTax.country=self.listObject[0]
			self.selectedTax.code=self.taxValues[1].get().encode("utf-8")   
			self.selectedTax.designation=self.taxValues[2].get().encode("utf-8")   
			self.selectedTax.rate=self.taxValues[3].get().encode("utf-8")            
			self.selectedTax.dateIn=self.getDateTimeInTax()
			self.selectedTax.dateOut=self.getDateTimeOutTax()
			self.searchTax()
		self.deleteTaxBt.config(state=DISABLED)
		self.clearFieldTax()

	def deleteTax(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer la Tax %s ?\nCette opération est irréversible !" % self.selectedTax.designation):
			Tax.delete(self.selectedTax.id)
			self.searchTax()            
		self.deleteTaxBt.config(state=DISABLED)
		self.clearFieldTax()
	# FIN de la gestion du module Tax ------------------------------------------------------------------------------------------------------------------------

class TaxListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Taxes")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Tax-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Tax-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tTaxListGUI\tStart")
		self.makeListTax()

	def selectListTax(self, event):
		if self.listListTax.get(0)!="":
			result = Tax.select(Tax.q.id==self.idListListTax[int(self.listListTax.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.rate)
				self.destroy()

	def searchListTax(self, event=None):
		if self.searchListTaxValue.get() != "":
			self.listListTax.delete(0,END)
			self.idListListTax = []
			result = Tax.select(Tax.q.designation.startswith(self.searchListTaxValue.get().encode("utf-8")), orderBy=Tax.q.designation)
			for row in result:
				self.listListTax.insert(END, row.country.name+" - "+row.code+" - "+str(row.rate))
				self.idListListTax.append(row.id)
		else:
			self.listListTax.delete(0,END)
			self.idListListTax = []
			result = Tax.select(orderBy=Tax.q.designation)
			for row in result:
				self.listListTax.insert(END, row.country.name+" - "+row.code+" - "+str(row.rate))
				self.idListListTax.append(row.id)

	def makeListTax(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des Taxes").pack(side=TOP, fill=X)
		self.searchListTaxValue = StringVar()
		s = Frame(leftFrame)
		self.searchListTaxEt = Entry(s,  width=25, textvariable=self.searchListTaxValue, relief=GROOVE)
		self.searchListTaxEt.bind("<KeyRelease>", self.searchListTax)
		self.searchListTaxEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListTaxEt, u"Saisir les premiéres lettres de la designation d'une Taxe d'un Séjour\npour une recherche plus précise,\nla liste est classée par Désignation.")
		newTaxBt=Button(s, image=self.imgNew, command=self.ctrlTax)
		newTaxBt.pack(side=RIGHT)
		self.balloon.bind(newTaxBt, u"Créer une nouvelle Taxe")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame)
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListTax = Listbox(s)
		self.listListTax.config(yscrollcommand=scrollbar.set,width=30, selectmode=SINGLE, height=16)
		self.listListTax.bind("<ButtonRelease-1>",self.selectListTax)
		scrollbar.config(command=self.listListTax.yview)
		self.listListTax.pack()
		self.balloon.bind(self.listListTax, u"Séléctionner une taxe.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListTax()

	def ctrlTax(self):
		TaxGUI(balloon=self.balloon, log=self.log, path=self.path)